#!/usr/bin/env python
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
import logging

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from django.utils import simplejson

import forms
import models
from controllers import handlers

class TransactionListHandler(handlers.AppHandler):

  def get(self):
    pass

class AddTransactionHandler(handlers.AppHandler):

  def ProcessCreateRpc(self, multi_dict):
    # participants
    participant_names = multi_dict.get("participants").split(",")
    logging.info("participant_names: " + str(participant_names))
    participants = []
    for name in participant_names:
      logging.info("name: " + name)
      participant = models.GroupMembership.all().filter("member_nickname =", name).get()
      logging.info("participant: " + str(participant))
      participants.append(participant)
    
    name = multi_dict.get("title")
    total = int(multi_dict.get("total"))
    payer = multi_dict.get("payer")
    group_membership = models.GroupMembership.GetMemberByNickname(payer)
    logging.info("group_membership: " + simplejson.dumps(group_membership.data()))
    person = group_membership.person
    
    line = [int(val) for val in multi_dict.get("line").split(",")]
    group_id = int(multi_dict.get("group_id"))
    group = models.Group.get_by_id(group_id)
    previous_transaction = models.Transaction.GetMostRecentTransaction(
      group.key().id())
    
    transaction = models.Transaction(name=name, group=group,
                                     txn_date=datetime.date.today(),
                                     payer=person, total_amount_micros=total)
    transaction.put()
    transaction.AddLine(participants, line, previous_transaction)
    callback = multi_dict.get("callback")
    jsonp = handlers.jsonp_render(transaction.data(), callback)
    self.response.out.write(jsonp)

  def get(self):
    self.ProcessCreateRpc(self.request.GET)
